package vip.george.sse;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
public class SseController {

    private final ExecutorService executor = Executors.newSingleThreadExecutor();

    @GetMapping(value = "/sse/time", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamTime() {
        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE); // 设置超时时间为无限

        // 设置完成和超时处理器
        emitter.onCompletion(() -> System.out.println("SSE连接完成"));

        executor.execute(() -> {
            try {
                for (int i = 0; i < 10; i++) { // 发送10次后自动结束
                    // 构造要发送的数据
                    String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    String message = "当前时间: " + time + " (消息 " + (i + 1) + ")";

                    // 发送数据
                    emitter.send(SseEmitter.event()
                            .data(message)
                            .id(String.valueOf(i))
                            .name("time-update"));
                    System.out.println("发送数据: " + message);
                    // 等待10秒
                    Thread.sleep(2000);
                }

                // 发送完成事件
                emitter.send(SseEmitter.event()
                        .data("事件流结束")
                        .name("complete"));

                // 完成
                emitter.complete();
            } catch (IOException | InterruptedException e) {
                emitter.completeWithError(e);
            }
        });


        emitter.onTimeout(() -> System.out.println("SSE连接超时"));

        return emitter;
    }
}
